package com.Xht.www.servlet;

//后端响应更新用户信息的请求

import com.Xht.www.po.UserInfoPO;
import com.Xht.www.service.User;
import com.Xht.www.serviceImpl.UserImpl;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.JsonObject;

@WebServlet("/updateUserInfo")
public class UpdateUserInfoServlet extends HttpServlet {

    private final User userService = new UserImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        StringBuilder jsonBuilder = new StringBuilder();
        String line;

        try (BufferedReader reader = req.getReader()) {
            while ((line = reader.readLine()) != null) {
                jsonBuilder.append(line);
            }
        } catch (IOException e) {
            resp.getWriter().write("{\"success\":false,\"message\":\"读取请求体失败\"}");
            return;
        }

        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(jsonBuilder.toString(), JsonObject.class);

        // 获取用户 ID
        int userId = jsonObject.get("userId").getAsInt();

        // 从数据库中获取当前用户的信息，包括 user_status
        UserInfoPO currentUser = userService.getUserById(userId);
        if (currentUser == null) {
            resp.getWriter().write("{\"success\":false,\"message\":\"用户不存在\"}");
            return;
        }

        UserInfoPO user = new UserInfoPO();
        user.setUserId(userId);
        user.setUsername(jsonObject.get("username").getAsString());
        user.setPassword(jsonObject.has("password") ? jsonObject.get("password").getAsString() : null);
        user.setGender(jsonObject.get("gender").getAsString());
        user.setAge(jsonObject.get("age").getAsInt());
        user.setBirthday(java.sql.Date.valueOf(jsonObject.get("birthday").getAsString()));

        // 保持 user_status 不变
        user.setUserStatus(currentUser.getUserStatus());

        boolean result = userService.updateUser(user);

        if (result) {
            resp.getWriter().write("{\"success\":true,\"message\":\"更新成功\"}");
        } else {
            resp.getWriter().write("{\"success\":false,\"message\":\"更新失败\"}");
        }
    }
}
